package com.cy.lib.redis.core.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.aspectj.apache.bcel.util.ClassPath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import redis.clients.jedis.Jedis;

@SuppressWarnings({"unchecked","rawtypes"})
public class RedisLuaUtil {

	private List<String> pathList;
	
	public static Map<String,DefaultRedisScript> luaMap = new HashMap<String, DefaultRedisScript>();
	

	@Autowired
	private RedisTemplate redisTemplate;

	public void setRedisTemplate(RedisTemplate redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
	
	public RedisLuaUtil(List<String> pathList){
		this.pathList = pathList;
	}
	
	
	public void init(){
		for(final String e:pathList){
			Object ret = redisTemplate.execute(new RedisCallback() {

				public Object doInRedis(RedisConnection connection) throws DataAccessException {
					Jedis jedis = (Jedis)connection.getNativeConnection();
					DefaultRedisScript script = new DefaultRedisScript();
					script.setScriptSource(new ResourceScriptSource(new ClassPathResource(e)));
					jedis.scriptLoad(script.getScriptAsString());
					return script;
				}
			},true);
			luaMap.put(e, (DefaultRedisScript)ret);
		}
	}
}
